<?

$host="localhost:8889";
$user="root";
$pass="root";
$db_name="darmedic";
#$sms_host="http://192.168.62.200";
#####################
$connection = mysql_connect($host, $user, $pass)  or die("Brak po��czenia z baz� danych.");
mysql_set_charset('utf8',$connection);
$db = mysql_select_db($db_name, $connection)  or die("Nie mo�na wybra� bazy danych");
#####################
##baza danych
require("/Applications/MAMP/htdocs/darmedicus/darmedic/library/config.inc.php");
require("/Applications/MAMP/htdocs/darmedicus/darmedic/library/Database.singleton.php");

// create the $db singleton object
$db = Database::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$db->debug = true;
$db->connect();
#pobranie danych globalnych
$glob="select * from globals where akt = 1";
$rows = $db->fetch_array($glob);
#śprint_r($rows);
foreach($rows as $record){
    $_SESSION['global'][$record[nazwa]]=$record[wartosc];
}
#$db->query('SET GLOBAL max_allowed_packet=67108864');
##


function html()
{
echo '<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/style.css" type="text/css" />
<link rel="stylesheet" href="css/site.forms.css" type="text/css" />
<link rel="stylesheet" href="css/admin.css" type="text/css" />
<link rel="stylesheet" href="css/kompio.css" type="text/css" />
<link rel="stylesheet" href="css/bubble-tooltip.css" media="screen">
<script type="text/javascript" src="js/bubble-tooltip.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.validate.js" charset=”ISO-8859-1″></script>
<script src="js/jquery.bestupper.min.js" type="text/javascript"></script> 
<link type="text/css" href="css/jquery.ui.all.css" rel="stylesheet" />
 <script type="text/javascript" src="js/jquery-ui.js"></script>
 <script type="text/javascript" src="js/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<title>.....DARMEDICUS......</title>';
echo '<style type="text/css">';
echo 'form#fancy fieldset{border-color: #ce0c0c;}';
echo '</style>';
echo'</head>';
echo'<body bgcolor="#FFFFFF">';
};
##
function form_auto_submit_2n  ($nazwa, $wartosci, $selected=0) {

#echo '<form method="post" action="'.$action.'">';	
echo  '<select name="'.$nazwa.'" class="butt2">';
foreach ($wartosci as $ind => $wart) {
echo '<option value="'.$ind.'" ';
if ($ind==$selected) echo 'selected="selected"';
echo '>'.$wart.'</option>';	
}
echo '</select>';
}

##
function logg ($tresc, $user){
	$tresc=addslashes($tresc);
$sql="insert into log values (CURRENT_TIMESTAMP, '".$user."', ('".$tresc."'))";	
mysql_query($sql);
#echo $sql;
#error_log(date("Y-m-d h:i:s")."||".$user."||".$tresc."\r\n", 3, 'darmedicus.log');
}
##
function form_auto_submit_2m  ($nazwa, $wartosci, $selected=0) {

#echo '<form method="post" action="'.$action.'">';	
echo  '<select name="'.$nazwa.'" id="'.$nazwa.'" class="butt2"> onchange="this.form.submit();">';
if ($wartosci<>''){
foreach ($wartosci as $ind => $wart) {
echo '<option value="'.$ind.'" ';
if ($ind==$selected) echo 'selected="selected"';
echo '>'.$wart.'</option>';	
}
}
echo '</select>';
}

function form_auto_submit_2mi  ($nazwa, $wartosci, $selected=0) {

#echo '<form method="post" action="'.$action.'">';	
echo  '<select name="'.$nazwa.'" id="'.$nazwa.'" class="butt2">';
if ($wartosci<>''){
foreach ($wartosci as $ind => $wart) {
echo '<option value="'.$ind.'" ';
if ($ind==$selected) echo 'selected="selected"';
echo '>'.$wart.'</option>';	
}
}
echo '</select>';
}
##


function zmienne()
{
 echo'<pre>';
 echo 'tablica session<br><br>';
 print_r($_SESSION);
 echo '<hr>tablica post<br><br>';
 print_r($_POST);
 echo '<hr>tablica get<br><br>';
 print_r($_GET);
 echo '<hr>tablica cookie<br><br>';
 print_r($_COOKIE);
 echo'</pre>';
        }
##############################
function data_zero ($a)
{
        if (strlen($a)==1) {$b='0'.$a;
        return $b;
        }
        else
        return $a;
        }
###############################
function form_auto_submit  ($action = 'index.php', $nazwa, $wartosci, $selected=0) {

echo '<form method="post" action="'.$action.'">';	
echo  '<select name="'.$nazwa.'" class="butt2" onchange="this.form.submit();">';
foreach ($wartosci as $ind => $wart) {
echo '<option value="'.$ind.'" ';
if ($ind==$selected) echo 'selected="selected"';
echo '>'.$wart.'</option>';	
}
echo '</select></form>';
}
###############################
#######################################################################
function get_name ($table, $id, $column='nazwa', $id_column='id')
{
$sql="select * from ".$table." where ".$id_column." = '".$id."';";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);

$sql="select ".$column." from ".$table." where ".$id_column." = '".$id."';";

$result = mysql_query($sql);
$row=mysql_fetch_row($result);
$id=$row[0];
return $id;
}

#######################################################################
function check_pac_ubezp($pac_id) {
    $sql = "select * from pac_ubezp where id_pac = ".$pac_id." and data = '".$_SESSION['data']."'";
    //echo $sql;
    $result = mysql_query($sql);
    $num_rows = mysql_num_rows($result);
    if($num_rows > 0){
      $row=mysql_fetch_row($result);
      $a[0]=$row[2];
      $a[1]=$row[3];
      return $a;
        }
    elseif (date('Y-m-d') == $_SESSION['data']){
       $ewus_odp = check_ewus ($pac_id, $_SESSION['global']['eWUS_login'], $_SESSION['global']['eWUS_password']);
       //print_r($ewus_odp);
       if (is_array($ewus_odp)==true){
           $sql = "insert into pac_ubezp values ('".$ewus_odp[0]."', '".$ewus_odp[1]."', '".$ewus_odp[2]."', '".$ewus_odp[3]."', '".$ewus_odp[4]."')";
           //echo $sql;
           mysql_query($sql);
           $b[0]=$ewus_odp[2];
           $b[1]=$ewus_odp[3];
           return $b;
       }
       else {
           $c[0]='-1';
           $c[1]=$ewus_odp;
           return $c;
       }
       //check_pac_ubezp($pac_id);
    }
    else {
        $d[0]='-1';
        $d[1]='Inna data nie można sprawdzić';
        return $d;
    }
}
#######################################################################
function check_ewus ($pac_id, $username, $password){
    $pac_pesel = get_name('pac', $pac_id, 'pac_pesel', 'id');
    if ($pac_pesel == '') return 'Niepoprawny nr PESEL';
    $params = array(
    'credentials' => array(
    array('name' => 'domain', 'value' => array('stringValue' => '07')),
    array('name' => 'login', 'value' => array('stringValue' => $username))
    ),
    'password' => $password);
    try { 
    $clientAuth = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl', array('trace' => true));
    $clientAuth->__soapCall('login', array($params), null, null, $loginHeaders);
    
    $date = date('Y-m-d\TH:i:s.BP'); 
    $xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:com="http://xml.kamsoft.pl/ws/common" xmlns:brok="http://xml.kamsoft.pl/ws/broker">
    <soapenv:Header>
    <com:session id="' . $loginHeaders['session']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/>
    <com:authToken id="' . $loginHeaders['authToken']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/>
    </soapenv:Header>
    <soapenv:Body>
    <brok:executeService>
    <com:location>
    <com:namespace>nfz.gov.pl/ws/broker/cwu</com:namespace>
    <com:localname>checkCWU</com:localname>
    <com:version>2.0</com:version>
    </com:location>
    <brok:date>'.$date.'</brok:date>
    <brok:payload>
    <brok:textload>
    <ewus:status_cwu_pyt xmlns:ewus="https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2">
    <ewus:numer_pesel>'.$pac_pesel.'</ewus:numer_pesel>
    <ewus:system_swiad nazwa="eWUS" wersja="2.0"/>
    </ewus:status_cwu_pyt>
    </brok:textload>
    </brok:payload>
    </brok:executeService>
    </soapenv:Body>
    </soapenv:Envelope>';
     
    $clientBroker = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker?wsdl', array('trace' => true, 'exceptions' => true));
    $r = $clientBroker->__doRequest($xml, 'https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker', 'executeService', SOAP_1_1);

    $doc = new DOMDocument();
    $doc->loadXML($r);
    
    $blad = $doc->getElementsByTagName('faultstring')->item(0);
    if ($blad<>'') {
	return $blad->nodeValue;
	}
    else {
    $match = $doc->getElementsByTagName('status_cwu_odp');
    $foundXML = $doc->saveXML($match->item(0));	
    $xpath = new DOMXpath($doc);
    $xpath->registerNamespace('odp','https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2');
    $operId = $xpath->query("//odp:status_cwu_odp")->item(0)->getAttribute('id_operacji');
    //file_put_contents($operId . '.xml', $foundXML);
    $elements = $xpath->query("//odp:status_ubezp");
    $status_ubezp = $elements->item(0)->nodeValue;
    $status_ub[0]=$pac_id;
    $status_ub[1]=date('Y-m-d');
    $status_ub[2]=$status_ubezp;
    $status_ub[3]=$operId;
    $status_ub[4]=$foundXML;
    return $status_ub;
	}    
    }
 catch (Exception $e){
    return $e->faultstring;
    }
}


?>